#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

vector<int> minp, primes;

void sieve(int n) {
    minp.assign(n + 1, 0);
    primes.clear();
    for (int i = 2; i <= n; i++) {
        if (minp[i] == 0) {
            minp[i] = i;
            primes.push_back(i);
        }
        for (auto p : primes) {
            if (1LL * i * p > n) break;
            minp[i * p] = p;
            if (p == minp[i]) break;
        }
    }
}

unordered_set<int> get_factors(int x) {
    unordered_set<int> factors;
    if (x < 2) return factors;
    if (x <= 2e5+5) {
        while (x > 1) {
            int p = minp[x];
            factors.insert(p);
            while (x % p == 0) x /= p;
        }
    } else {
        for (auto p : primes) {
            if (1LL * p * p > x) break;
            if (x % p == 0) {
                factors.insert(p);
                while (x % p == 0) x /= p;
            }
        }
        if (x > 1) factors.insert(x);
    }
    return factors;
}

void solve(){
    int n;
    cin >> n;
    vector<pair<int,ll>> a(n + 1); 
    vector<ll> odd;
    for (int i = 1; i <= n; i++) cin >> a[i].first;
    for (int i = 1; i <= n; i++) cin >> a[i].second;

    unordered_map<int, int> mp;
    for (int i = 1; i <= n; i++) {
    	if(a[i].first&1)odd.push_back(a[i].second);
        auto f = get_factors(a[i].first);
        for (auto p : f) {
            mp[p]++;
            if (mp[p] >= 2) {
                cout << 0 << '\n';
                return;
            }
        }
    }

    sort(odd.begin(),odd.end());
    ll res=0x3f3f3f3f;

   	if(mp[2] == 1){
   		res = odd[0];
   	}else{
   		res = odd[0] + odd[1];
   	}

   	// cout<<res<<'\n';

    sort(a.begin()+1,a.end(),[&](pair<int,ll> a,pair<int,ll> b){
    	return a.second<b.second;
    });


    vector<int> temp;
    for (auto& [p, cnt] : mp) {
        if (cnt == 1) {
            temp.push_back(p);
        }
    }
    
    for (int i = 1; i <= n; i++) {
    	if(temp.empty())break;
	    for (int p : temp) {
	        int r = a[i].first % p;
	        int j = (r == 0) ? 0 : (p - r);
	        if (j == 0) continue;

	        if (1LL * j * a[i].second >= res) continue;

	        if ((a[i].first + j) % p == 0) {
	            res = min(res, 1LL * j * a[i].second);
	        }
	    }
	}

    cout<<res<<'\n';
    // cout<<'\n';
}

int main(){
    sieve(2e5 + 10);
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    int t=1;
    cin>>t;
    while(t--){
        solve();
    }
    return 0;
}